24. 两两交换链表中的节点
24. 两两交换链表中的节点
Similar Question
leading to the advanced question
Solution Tips
方案一: 迭代
swapPairs() {
const dummyHead = new Node(0);
dummyHead.next = this.head;
let cur = this.head;
let prev = dummyHead;
while (cur !== null && cur.next !== null) {
// cur 和 next 互换
const next = cur.next.next;
cur.next.next = cur;
prev.next = cur.next;
cur.next = next;
prev = cur;
cur = next;
};
this.head = dummyHead.next;
return dummyHead.next;
}
方案二: 递归
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}